package com.gitee.tanmingjian.httptunnel.autoconfigure;

import com.gitee.tanmingjian.httptunnel.core.HttpTunnelService;
import com.gitee.tanmingjian.httptunnel.core.util.BannerUtil;
import com.gitee.tanmingjian.httptunnel.handler.ReactiveHttpTunnelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;

import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED;

@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@EnableConfigurationProperties(NavicatHttpTunnelProperties.class)
public class ReactiveAutoConfiguration {

    private static final Logger log = LoggerFactory.getLogger(ReactiveAutoConfiguration.class);

    private final NavicatHttpTunnelProperties navicatHttpTunnelProperties;

    public ReactiveAutoConfiguration(NavicatHttpTunnelProperties navicatHttpTunnelProperties) {
        this.navicatHttpTunnelProperties = navicatHttpTunnelProperties;
        BannerUtil.printBanner();
    }

    @Bean
    public org.springframework.web.reactive.function.server.RouterFunction<org.springframework.web.reactive.function.server.ServerResponse> reactiveRouterFunction() {
        String mysqlBasePath = Optional.ofNullable(navicatHttpTunnelProperties.getBasePath()).orElse("").concat("/mysql");
        log.info("MySQL HTTP Tunnel started on {} and {}/{sessionId}", mysqlBasePath, mysqlBasePath);
        HttpTunnelService httpTunnelService = new HttpTunnelService();
        ReactiveHttpTunnelHandler httpTunnelHandler = new ReactiveHttpTunnelHandler(mysqlBasePath, httpTunnelService);
        return org.springframework.web.reactive.function.server.RouterFunctions.route()
                .GET(mysqlBasePath, httpTunnelHandler::index)
                .POST(mysqlBasePath, org.springframework.web.reactive.function.server.RequestPredicates.accept(APPLICATION_FORM_URLENCODED), httpTunnelHandler::post)
                .POST(mysqlBasePath + "/{sessionId}", org.springframework.web.reactive.function.server.RequestPredicates.accept(APPLICATION_FORM_URLENCODED), httpTunnelHandler::post)
                .build();
    }

}
